package com.zg.invoice.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zg.invoice.vo.OpenInvoiceReq;
import com.zg.invoice.vo.leqi.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

/**
 * 乐企发票系统
 */
@Component
@Slf4j
@RefreshScope
public class LeqiApiUtil {

    @Value("${invoice.leqi.requestUrl}")
    private  String url ;


    /**
     * 开票请求
     * @param openInvoiceReq
     * @return
     */
    public LeqiOpenInvoiceRes sendOpenInvoice(OpenInvoiceReq openInvoiceReq){
        String resultStr = HttpUtil
                .createPost(url +"/api/saveInvoice")
                .contentType("application/json;charset=UTF-8")
                .body(JSON.toJSONString(openInvoiceReq))
                .execute().body();
        log.info("请求地址："+url+";请求参数："+ JSON.toJSONString(openInvoiceReq));
        log.info("响应结果："+resultStr);
        LeqiOpenInvoiceRes openInvoiceRes = JSON.toJavaObject(JSON.parseObject(resultStr), LeqiOpenInvoiceRes.class);
        return openInvoiceRes;
    }

    /**
     *发票红冲
     */
    public LeqiInvoiceRedRes sendInvoiceRed(LeqiInvoiceRedReq invoiceRedReq){
        String result = HttpUtil
                .createPost(url+"/api/sqHcInvoice")
                .contentType("application/json;charset=utf-8")
                .body(JSONObject.toJSONString(invoiceRedReq))
                .execute()
                .body();
        log.info("发票红冲请求报文:"+invoiceRedReq.toString());
        log.info("发票红冲返回报文"+result);
        LeqiInvoiceRedRes invoiceRedRes = JSON.toJavaObject(JSON.parseObject(result), LeqiInvoiceRedRes.class);
        log.info("转成对象："+invoiceRedRes.toString());
        return invoiceRedRes;
    }

    /**
     *查询发票信息
     */
    public InvoiceRedRes queryInvoice(QueryInvoiceReq queryInvoiceReq){
        String result = HttpUtil
                .createPost(url+"/api/getInvoice")
                .contentType("application/json;charset=utf-8")
                .body(JSONObject.toJSONString(queryInvoiceReq))
                .execute()
                .body();
        log.info("发票信息查询请求报文:{}", JSONUtil.toJsonStr(queryInvoiceReq));
        log.info("发票信息查询返回报文:{}",result);
        InvoiceRedRes invoiceRedRes = JSON.toJavaObject(JSON.parseObject(result), InvoiceRedRes.class);
        log.info("发票信息查询转成对象：{}", JSONUtil.toJsonStr(invoiceRedRes));
        return invoiceRedRes;
    }

}
